const mongoose = require("mongoose");

const CONFIG = require("./config/index");
const { DBUSER, DBPWD, DBHOST, DBPORT, DBNAME } = CONFIG;
const url = `mongodb://${DBUSER}:${DBPWD}@${DBHOST}:${DBPORT}/${DBNAME}`;

/**
 *
 * @param {* 执行成功的回调} suceess
 * @param {* 执行失败的回调} error
 */
module.exports = function (suceess, error) {
  if (typeof error != "function") {
    console.log("语法错误");
    error = () => {};
  }

  console.log("url", url);
  // 建立连接
  mongoose.connect(url);

  // 监听连接成功
  mongoose.connection.once("open", () => {
    console.log("mongodb 连接成功");
    suceess();
  });

  // 监听连接失败
  mongoose.connection.once("error", (err) => {
    console.log("mongodb 连接失败", err);
    error(err);
  });
  // 监听连接关闭
  mongoose.connection.once("close", () => {
    console.log("mongodb 连接关闭");
  });
};
